<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label-width="120px" label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="用户昵称（多个用,分割）"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label-width="120px" label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label-width="120px" label="代理等级" prop="szAgency">
        <el-select v-model="queryParams.szAgency" placeholder="请选择代理等级" clearable size="small">
          <el-option
            v-for="dict in agencyOptions"
            :key="dict.dmcod"
            :label="dict.dmcpt"
            :value="dict.dmcod"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="120px" label="钱包余额" prop="szWalletBalance">
        <el-input
          type="number"
          v-model="queryParams.szWalletBalance"
          placeholder="请输入钱包余额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提现钱包余额" label-width="120px" prop="szWithdrawalBalance">
        <el-input
          type="number"
          v-model="queryParams.szWithdrawalBalance"
          placeholder="请输入提现钱包余额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提现冻结金额" label-width="120px" prop="frozenAccount">
        <el-input
          type="number"
          v-model="queryParams.frozenAccount"
          placeholder="请输入提现冻结金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="可用能量值" label-width="120px" prop="szEnergy">
        <el-input
          type="number"
          v-model="queryParams.szEnergy"
          placeholder="请输入可用能量值"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label-width="120px" label="是否开通" prop="szAgency">
        <el-select v-model="queryParams.szEnable" placeholder="请选择开通状态" clearable size="small">
          <el-option
            v-for="dict in szEnableOptions"
            :key="dict.dmcod"
            :label="dict.dmcpt"
            :value="dict.dmcod"
          />
        </el-select>
      </el-form-item>

      <el-form-item label-width="120px" label="账号状态" prop="isSignOut">
        <el-select v-model="queryParams.isSignOut" placeholder="账号状态" clearable size="small">
          <el-option
            v-for="dict in signOutOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label-width="120px" label="直播状态" prop="isFrozen">
        <el-select v-model="queryParams.isFrozen" placeholder="直播状态" clearable size="small">
          <el-option
            v-for="dict in frozenOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-shopping-bag-2"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['finance:livestreaming:createOrder']"
        >购买产品</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-sell"
          size="mini"
          @click="handleAddMM"
          v-hasPermi="['finance:livestreaming:buy']"
        >购买产品(免支付)</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-goods"
          size="mini"
          @click="handleAddDK"
          v-hasPermi="['finance:livestreaming:deductionBuyLivestreaming']"
        >购买产品(抵扣支付)</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-share"
          size="mini"
          @click="handleDuiChong"
          v-hasPermi="['finance:livestreaming:mutualRecharge']"
        >对冲产品</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleDuiChong2"
          v-hasPermi="['finance:livestreaming:mutualRechargeBalance']"
        >对冲提现余额</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-sell"
          size="mini"
          @click="handleTixian"
          v-hasPermi="['finance:livestreaming:balanceWithdrawal']"
        >提现</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-sell"
          size="mini"
          @click="handleDashang"
          v-hasPermi="['finance:livestreaming:rewardWithGifts']"
        >打赏模拟</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['finance:livestreaming:export']"
        >导出</el-button>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleH5"
          v-hasPermi="['finance:livestreaming:createOrderH5']"
        >H5支付</el-button>
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表数据 -->
    <el-table border v-loading="loading" :data="livestreamingList" :cell-style="columnStyle" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="昵称" align="center" prop="nickname" fixed="left"/>
      <el-table-column label="手机号" width="120" align="center" prop="phone" />
      <el-table-column label="账号类型" width="80" align="center" prop="accountType" />
      <el-table-column label="是否开通数字直播" width="130" align="center" prop="tag">
        <template slot-scope="scope">
            <el-tag
              v-if="scope.row.szEnable === '1'"
              type="success"
              disable-transitions>{{scope.row.szEnableName}}</el-tag>
            <el-tag
              v-else-if="scope.row.szEnable === '2'"
              type="warning"
              disable-transitions>{{scope.row.szEnableName}}</el-tag>
            <el-tag
              v-else
              type="danger"
              disable-transitions>{{scope.row.szEnableName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="产品购买次数" width="110" align="center" prop="enableCount" />
      <el-table-column label="代理等级" width="80" align="center" prop="szAgencyName" />
      <el-table-column label="账号状态" align="center" prop="signOutName" width="160">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isSignOut === '0'">{{ scope.row.signOutName }}</el-tag>
          <el-tag v-else type="info">{{ scope.row.signOutName }}<br>{{ scope.row.signOutTime }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="直播状态" align="center" prop="frozenName" width="160">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isFrozen === '0'">{{ scope.row.frozenName }}</el-tag>
          <el-tag v-else type="info">{{ scope.row.frozenName }}<br>{{ scope.row.frozenTime }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="最近登录时间" width="180" align="center" prop="lastLoginTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="钱包余额" width="80" align="center" prop="szWalletBalance" />
      <el-table-column label="待激活余额" width="100" align="center" prop="pendingActivationBalance" />
      <el-table-column label="提现钱包余额" width="120" align="center" prop="szWithdrawalBalance" />
      <el-table-column label="提现冻结金额" width="120" align="center" prop="frozenAccount" />
      <el-table-column label="待抵扣金额" width="100" align="center" prop="deductionAmount" />
      <el-table-column label="可用能量值" width="100" align="center" prop="szEnergy" />
      <el-table-column label="团队奖励累计收益" width="130" align="center" prop="szTeamReward" />
      <el-table-column label="极差奖励累计收益" width="130" align="center" prop="szRangeReward" />
      <el-table-column label="平级奖励累计收益" width="130" align="center" prop="szLateralReward" />
      <el-table-column label="复购奖励累计收益" width="130" align="center" prop="szRepeatbuyReword" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleShowInvite(scope.row)"
            v-hasPermi="['finance:livestreaming:userInviteTree']"
          >邀请人</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleShowPurchaseRecord(scope.row)"
            v-hasPermi="['finance:livestreaming:purchaseRecordToAdmin']"
          >购买记录</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleShowBalance(scope.row)"
            v-hasPermi="['finance:livestreaming:balanceDetailAdmin']"
          >余额变动</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleShowWithdrawalBalance(scope.row)"
            v-hasPermi="['finance:livestreaming:withdrawalBalance']"
          >提现余额明细</el-button>

          <el-button
            size="mini"
            type="text"
            :icon="scope.row.isFrozen === '0' ? 'el-icon-video-pause' : 'el-icon-video-play'"
            @click="frozenOrEnable(scope.row)"
            v-hasPermi="['finance:livestreaming:frozenOrEnable']"
          >冻结/开启</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-star-off"
            @click="vipUpgradeRecord(scope.row)"
            v-hasPermi="['finance:livestreaming:updateUserVip']"
          >代理等级</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="deductionRecord(scope.row)"
            v-hasPermi="['finance:livestreaming:updateDeduction']"
          >抵扣还款</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-row >
      <div style="margin-top:20px">
        <h2 style="line-height: 30px;">钱包余额总计：{{szWalletBalanceSum}}元</h2>
        <h2 style="line-height: 30px;">提现钱包余额总计：{{szWithdrawalBalanceSum}}元</h2>
      </div>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- H5支付 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisibleH5"
      width="35%">

      <div>
        <form id="payForm" action="https://cashier1.sandpay.com.cn/gw/web/order/create" method="post" target="_blank">
            <p>
                <label>
                    报文签名 ↓↓↓↓↓↓↓↓↓↓↓↓↓
                </label>
                <br/>
                编码方式
                <input v-model="test1" class="a" type="text" name="charset" id="charset"/>
                <br/>
                交易报文
                <input v-model="test2"  class="a" type="text" name="data" id="data"/>
                <br/>
                签名类型
                <input v-model="test3"  class="a" type="text" name="signType" id="signType" />
                <br/>
                签名
                <input v-model="test4" class="a" type="text" name="sign" id="sign"/>
                <br/>
                扩展域
    <!--            <input class="a" type="text" name="extend" id="extend" value=""/>-->
                <br/>
                <button type="submit"> 下单</button>
                &nbsp;
            </p>
        </form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleH5 = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 购买弹框 -->
    <el-dialog :title="title" :visible.sync="bugOpen" width="25%" append-to-body>
      {{ nickName }}
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="购买人" prop="user_id">
          <el-select @change="handleUserChange" v-model="form.user_id" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邀请人" prop="parent_id">
          <el-select :disabled="disableParentSelect" v-model="form.parent_id" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="buy_type">
          <el-input :disabled="true" v-model="form.buy_type" placeholder="支付金额" style="width: 90%" />
        </el-form-item>
        <el-form-item label="获得能量值" prop="energy">
          <el-input :disabled="true" v-model="form.energy" placeholder="能量值" style="width: 90%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 购买直播产品 支付弹窗 -->
    <el-dialog :visible.sync="dialogVisibleOrder" title="订单详情" width="30%" >
      <div class="order-info">
        <p><strong class="order-info-left">订单名称:</strong> {{ orderInfo.orderName }}</p>
        <p><strong class="order-info-left">订单描述:</strong> {{ orderInfo.orderDescription }}</p>
        <p><strong class="order-info-left">订单编号:</strong> {{ orderInfo.orderId }}</p>
        <p><strong class="order-info-left">过期时间:</strong> {{ orderInfo.expirationTime }}</p>
      </div>
      <div class="payment-qrcode">
        <img :src="orderInfo.PaymentQRCode" alt="支付二维码">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOrder = false">关闭</el-button>
      </span>
    </el-dialog>


    <!-- 购买弹框 抵扣支付-->
    <el-dialog title="购买数字人直播（抵扣支付）" :visible.sync="bugOpenDK" width="35%" append-to-body>
      {{ nickName }}
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="购买人" prop="user_id">
          <el-select @change="handleUserChange" v-model="form.user_id" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邀请人" prop="parent_id">
          <el-select :disabled="disableParentSelect" v-model="form.parent_id" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" type="number" @input="changeAmount" placeholder="支付金额" style="width: 90%" />
        </el-form-item>
        <el-form-item label="抵扣金额" prop="deductionAmount">
          <el-input :disabled="true" v-model="form.deductionAmount" placeholder="抵扣金额" style="width: 90%" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitFormDK">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对冲产品弹框 -->
    <el-dialog title="对冲产品" append-to-body
      :visible.sync="duichongDialogVisible"
      width="30%"
      >
      <el-form ref="duichongForm" :rules="duichongRules" :model="duichongForm" label-width="90px">
        <el-form-item label="支付人" prop="fromUser">
          <el-select v-model="duichongForm.fromUser" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买人" prop="toUser">
          <el-select v-model="duichongForm.toUser" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="buy_type">
          <el-input :disabled="true" v-model="duichongForm.buy_type" placeholder="支付金额" style="width: 90%" />
        </el-form-item>
        <el-form-item label="扣除能量值" prop="energy">
          <el-input :disabled="true" v-model="duichongForm.energy" placeholder="能量值" style="width: 90%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitFormDuiChong">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对冲提现余额弹框 -->
    <el-dialog title="对冲提现余额" append-to-body
      :visible.sync="duichongDialogVisible2"
      width="30%"
      >
      <el-form ref="duichongForm2" :rules="duichongRules2" :model="duichongForm2" label-width="90px">
        <el-form-item label="支付人" prop="fromUser">
          <el-select v-model="duichongForm2.fromUser" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接受人" prop="toUser">
          <el-select v-model="duichongForm2.toUser" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="money">
          <el-input type="number" v-model="duichongForm2.money" placeholder="充值金额" style="width: 90%" />
        </el-form-item>
        <el-form-item label="支付密码" prop="paymentPassword">
          <el-input type="password" v-model="duichongForm2.paymentPassword" placeholder="支付密码" style="width: 90%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitFormDuiChong2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 提现弹框 -->
    <el-dialog title="提现" append-to-body
      :visible.sync="tixianDialogVisible"
      width="30%"
      >
      <el-form ref="tixianForm" :rules="tixianRules" :model="tixianForm" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="tixianForm.userId" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input type="number" v-model="tixianForm.amount" placeholder="提现金额" style="width: 90%" />
        </el-form-item>
        <el-form-item label="支付密码" prop="paymentPassword">
          <el-input type="password" v-model="tixianForm.paymentPassword" placeholder="支付密码" style="width: 90%" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="tixianForm.remark" placeholder="备注" style="width: 90%" />
        </el-form-item> -->
        <el-form-item label="税收比例" prop="revenueRatio">
          <el-input :disabled="true" v-model="tixianForm.revenueRatio" placeholder="税收比例" style="width: 90%" />
        </el-form-item>
        <el-form-item label="手续费" prop="extractRatio">
          <el-input :disabled="true" v-model="tixianForm.extractRatio" placeholder="手续费" style="width: 90%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitFormTixian">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打赏弹框 -->
    <el-dialog title="主播打赏" append-to-body
      :visible.sync="dashagnDialogVisible"
      width="33%"
      >
      <el-form ref="dashangForm" :rules="dashangRules" :model="dashangForm" label-width="60px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="dashangForm.userId" filterable placeholder="请选择" style="width: 90%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主播" prop="rewardedUser">
          <el-select v-model="dashangForm.rewardedUser" filterable placeholder="请选择主播" style="width: 90%">
            <el-option
              v-for="item in zbList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="礼物" prop="giftId">
          <el-select @change="changeGift()" v-model="dashangForm.giftId" filterable placeholder="请选择礼物" style="width: 90%">
            <el-option
              v-for="item in giftList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input type="number" :disabled="true" v-model="dashangForm.price" placeholder="单价" style="width: 90%" />
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input type="number" v-model="dashangForm.count" placeholder="数量" style="width: 90%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submittingLoding" @click="submitFormDashang">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看邀请人弹框 -->
    <el-dialog
      :title="dialogVisibleInviteTitle"
      :visible.sync="dialogVisibleInvite"
      width="60%">
      <div>
        <el-table
          :data="inviteUserList"
          style="width: 100%"
          row-key="id"
          border
          :tree-props="{children: 'children'}">
          <el-table-column
            prop="nickName"
            fixed="left"
            label="用户昵称"
            min-width="30%"
            >
          </el-table-column>
          <el-table-column
            align="center"
            prop="phone"
            label="手机号"
            min-width="20%"
            >
          </el-table-column>
          <el-table-column
            align="center"
            prop="vipName"
            label="代理等级"
            min-width="20%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="money"
            min-width="15%"
            label="充值金额/元">
          </el-table-column>
          <el-table-column
            align="center"
            prop="moneySum"
            min-width="15%"
            label="下级总充值金额/元">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleInvite = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 查看 购买记录 弹框 -->
    <el-dialog
      :title="dialogVisiblePurchaseRecordTitle"
      :visible.sync="dialogVisiblePurchaseRecord"
      width="75%">
      <div>
        <el-table
          :data="purchaseRecordList"
          border
          style="width: 100%;">
          <el-table-column
            align="center"
            min-width="7%"
            prop="payment_type"
            label="支付类型"
            >
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="buy_type"
            label="购买类型">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="recharge_amount"
            label="充值金额">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="actually_amount"
            label="实际支付金额">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="balance_pay_amount"
            label="组合支付金额">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="recharge_time"
            label="充值时间">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="15%"
            prop="pay_id"
            label="支付订单号">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="15%"
            prop="order_name"
            label="订单名称">
          </el-table-column>
          <el-table-column
            align="center"
            min-width="7%"
            prop="pay_state"
            label="订单状态">
          </el-table-column>
          <el-table-column
            min-width="7%"
            align="center"
            prop="remark"
            label="备注">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisiblePurchaseRecord = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 查看 余额明细 弹框 -->
    <el-dialog
      :title="dialogVisibleBalanceDetailTitle"
      :visible.sync="dialogVisiblBbalanceDetail"
      width="50%">
      <div>
        <MyStatistic
          style="padding-left: 20px; padding-bottom: 10px;"
          incomeTitle="余额总收入"
          disburseTitle="余额总支出"
          :income="income"
          :disburse="disburse"></MyStatistic>
        <el-table
          :data="balanceDetailList"
          border
          style="width: 100%;">
          <el-table-column
          min-width="20"
            align="center"
            label="流动类型">
            <template slot-scope="scope">
              <span style="margin-left: 10px"></span>
              <el-tag v-if="scope.row.typeId == '6'" type="primary">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == '7'" type="danger">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == '1'" type="warning">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == '20' || scope.row.typeId == '30' || scope.row.typeId == '40' || scope.row.typeId == '50'" type="info">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else type="success">{{ scope.row.flow_type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
          min-width="40"
            align="center"
            prop="nickname"
            label="购买人/被打赏人/操作人/产生人">
          </el-table-column>
          <el-table-column
          min-width="15"
            align="center"
            prop="money"
            label="具体金额">
          </el-table-column>
          <el-table-column
          min-width="25"
            align="center"
            prop="create_time"
            label="产生时间">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisiblBbalanceDetail = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 查看 提现余额明细 弹框 -->
    <el-dialog
      :title="withdrawalBalanceTitle"
      :visible.sync="withdrawalBalanceDialogVisible"
      width="50%">
      <div>
        <MyStatistic
          style="padding-left: 20px; padding-bottom: 10px;"
          incomeTitle="可提现余额总收入"
          disburseTitle="可提现余额总支出"
          :income="income"
          :disburse="disburse"></MyStatistic>
        <el-table
          :data="withdrawalBalanceList"
          border
          style="width: 100%;">
          <el-table-column
            min-width="19%"
            align="center"
            label="流动类型">
            <template slot-scope="scope">
              <span style="margin-left: 10px"></span>
              <el-tag v-if="scope.row.typeId == 1" type="success">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 3" type="warning">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 4" type="primary">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 5" type="primary">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 6" type="primary">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 7" type="danger">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 10" type="primary">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 9" type="danger">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 11" type="warning">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else-if="scope.row.typeId == 12" type="danger">{{ scope.row.flow_type }}</el-tag>
              <el-tag v-else type="danger">{{ scope.row.flow_type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            min-width="15%"
            align="center"
            prop="money"
            label="具体金额">
          </el-table-column>
          <el-table-column
            min-width="40%"
            align="center"
            prop="nickname"
            label="接受人/操作人/提现账号">
          </el-table-column>
          <el-table-column
            min-width="26%"
            align="center"
            prop="create_time"
            label="产生时间">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="withdrawalBalanceDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 修改VIP记录 -->
    <el-dialog
      title="代理等级"
      :visible.sync="dialogVisibleVIP"
      width="60%">
      <div>

        <el-form label-width="80px">
          <el-form-item label="当前等级" prop="extractRatio">
            <el-select v-model="selectVip" placeholder="请选择代理等级" clearable size="small">
              <el-option
                v-for="dict in agencyOptions"
                :key="dict.dmcod"
                :label="dict.dmcpt"
                :value="dict.dmcod"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <el-table
          :data="vipRecordList"
          style="width: 100%">
          <el-table-column
            align="center"
            prop="nickName"
            label="用户"
            min-width="20%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="createUser"
            label="变更类型"
            min-width="15%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="变更时间"
            min-width="20%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="beforeName"
            min-width="15%"
            label="变更前等级">
          </el-table-column>
          <el-table-column
            align="center"
            prop="afterName"
            min-width="15%"
            label="变更后等级">
          </el-table-column>
          <el-table-column
            align="center"
            prop="elapsedDay"
            min-width="15%"
            label="距离上次等级变化/天">
          </el-table-column>
        </el-table>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleVIP = false">取 消</el-button>
        <el-button :loading="submittingLoding" type="primary" @click="updateUserVip">修 改</el-button>
      </span>
    </el-dialog>


    <!-- 抵扣记录 -->
    <el-dialog
      title="抵扣金额还款"
      :visible.sync="dialogDeduction"
      width="58%">
      <div>

        <div style="padding:8px">
          <el-row>
            <el-col :span="5" class="centered-text"><b>可用提现钱包余额：{{ kyje }}</b></el-col>
            <el-col :span="4" class="centered-text">请输入还款金额:</el-col>
            <el-col :span="8" style="margin-top: -10px;">
              <el-input v-model="inputDeductionAmount" placeholder="请输入抵扣金额"></el-input>
            </el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </div>


        <el-table
          :data="deductionList"
          style="width: 100%;margin-top: 10px;">
          <el-table-column
            align="center"
            prop="nickname"
            min-width="20%"
            label="用户">
          </el-table-column>
          <el-table-column
            align="center"
            prop="typeName"
            min-width="15%"
            label="变更类型">
          </el-table-column>
          <el-table-column
            align="center"
            prop="amount"
            min-width="15%"
            label="金额">
          </el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="变更时间"
            min-width="20%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="befor_amount"
            label="变更前金额"
            min-width="15%">
          </el-table-column>
          <el-table-column
            align="center"
            prop="after_amount"
            label="变更后金额"
            min-width="15%">
          </el-table-column>
        </el-table>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeduction = false">取 消</el-button>
        <el-button :loading="submittingLoding" type="primary" @click="updateDeduction">还 款</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { deductionBuyLivestreaming,deductionAmountRecord,updateDeduction,
          updateUserVip,vipUpgradeRecord,frozenOrEnable,getSzanchor,getSzGift,mutualRechargeBalance,
          createOrderH5,orderPolling,createOrder,withdrawalBalance,balanceDetailAdmin,
          purchaseRecordToAdmin,rewardWithGifts, balanceWithdrawal,userInviteTree,mutualRecharge,
          listSzUserSimple,getOtherRule,dmcTable,listSzVipRule,listLivestreaming,
          buyLivestreaming, exportLivestreaming } from "@/api/finance/livestreaming";
import MyStatistic from './components/MyStatistic.vue'

export default {
  name: "Livestreaming",
  components: {MyStatistic},
  data() {
    return {
      nickName:'',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //钱包余额总计
      szWalletBalanceSum: 0,
      //钱包可提现余额总计
      szWithdrawalBalanceSum: 0,
      // 数字直播表格数据
      livestreamingList: [],
      // 弹出层标题
      title: "",
      // 购买类型
      bugType: 1,
      // 购买显示弹出层
      bugOpen: false,
      // 抵扣购买弹出层
      bugOpenDK: false,
      // 代理等级字典
      agencyOptions: [],
      // 开通状态
      szEnableOptions: [],
      // 购买人下拉框
      userOptions:[],
      // 邀请人人下拉框
      parentOptions:[],
      // 账号状态字典
      signOutOptions: [],
      // 直播状态字典
      frozenOptions: [],
      // 对冲产品弹框 弹出状态
      duichongDialogVisible: false,
      // 对冲提现余额弹框 弹出状态
      duichongDialogVisible2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        phone: null,
        szAgency: null,
        szWalletBalance: null,
        szWithdrawalBalance: null,
        frozenAccount: null,
        szEnergy: null,
        szEnable: null,
        isSignOut: null,
        isFrozen: null
      },
      // 购买产品 表单参数
      form: {
        user_id: "",
        parent_id: "",
        buy_type: null,
        energy: null,
        amount: null,
        deductionAmount: null
      },
      // 购买产品 表单校验
      rules: {
        user_id: [{ required: true, message: '请选择购买人', trigger: 'change' }],
      },
      // 对冲产品 提交数据
      duichongForm: {
        fromUser: "",
        toUser: "",
        buy_type: null,
        energy: null
      },
      // 对冲产品 表单校验
      duichongRules: {
        fromUser: [{ required: true, message: '请选择支付人', trigger: 'blur' }],
        toUser: [{ required: true, message: '请选择购买人', trigger: 'blur' }]
      },
      // 对冲提现余额 提交数据
      duichongForm2: {
        fromUser: "",
        toUser: "",
        money: null,
        paymentPassword: null
      },
      // 对冲提现余额 表单校验
      duichongRules2: {
        fromUser: [{ required: true, message: '请选择支付人', trigger: 'blur' }],
        toUser: [{ required: true, message: '请选择接受人', trigger: 'blur' }],
        money: [{ required: true, message: '请输入充值金额', trigger: 'blur' }],
        paymentPassword: [{ required: true, message: '请输入支付密码', trigger: 'blur' }]
      },
      // 提现 表单数据
      tixianForm: {
        userId: "",
        amount: "",
        paymentPassword: "",
        remark: "",
        revenueRatio: null,
        extractRatio: null
      },
      // 提现 表单校验
      tixianRules: {
        userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入提现金额', trigger: 'blur' }],
        paymentPassword: [{ required: true, message: '请输入支付密码', trigger: 'blur' }]
      },
      // 查看邀请人弹框
      dialogVisibleInvite: false,
      // 邀请人 待展示数据
      inviteUserList: [],
      dialogVisibleInviteTitle: '',
      // 提现弹框
      tixianDialogVisible: false,
      // 打赏提示框
      dashagnDialogVisible: false,
      // 打赏表单数据
      dashangForm: {
        userId: "",
        rewardedUser: "",
        giftId: "",
        price: "",
        count: ""
      },
      // 打赏表单校验规则
      dashangRules: {
        userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        rewardedUser: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        giftId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        price: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        count: [{ required: true, message: '请选择用户', trigger: 'blur' }]
      },
      // 控制确定按钮的 loading 状态
      submittingLoding: false,
      // 购买记录数据
      purchaseRecordList: [],
      // 购买记录弹框 标题
      dialogVisiblePurchaseRecordTitle: '',
      // 购买记录弹框展示隐藏
      dialogVisiblePurchaseRecord: false,
      // 余额明细数据
      balanceDetailList: [],
      // 余额明细弹出 标题
      dialogVisibleBalanceDetailTitle: '',
      // 余额明细弹框展示隐藏
      dialogVisiblBbalanceDetail: false,
      // 余额总收入
      income: '',
      // 余额总支出
      disburse:'',
      // 提现钱包细明 数据
      withdrawalBalanceList: [],
      // 提现钱包细明弹出 标题
      withdrawalBalanceTitle: '',
      // 提现钱包细明 展示隐藏
      withdrawalBalanceDialogVisible: false,
      dialogVisibleOrder: false,
      orderInfo:{
        orderName: '',
        orderDescription: '',
        orderId: '',
        expirationTime: '',
        PaymentQRCode: null
      },
      pollInterval: null, // 轮询定时器
      pollingCount: 0, // 轮询计数
      maxPollingCount: 600, // 最大轮询次数，相当于10分钟（每秒轮询一次）
      dialogVisibleH5: false,
      test1:'',
      test2:'',
      test3:'',
      test4:'',
      // 礼物下拉列表
      giftList: [],
      // 主播列表
      zbList: [],
      // 修改VIP等级
      dialogVisibleVIP: false,
      // VIP记录列表数据
      vipRecordList: [],
      // 所选修改后的代理等级
      selectVip:null,
      // 要修改的用户
      selectUser:null,
      // 抵扣金额弹出框
      dialogDeduction: false,
      // 可用金额
      kyje: 0,
      // 抵扣金额
      inputDeductionAmount: 0,
      // 抵扣金额变化记录弹框
      deductionList: []

    };
  },
  created() {
    clearInterval(this.pollInterval);
    this.getList();
    listSzVipRule().then(response => {
        this.agencyOptions = response.data;
    });
    this.getDicts("DMC016").then(response => {
      this.signOutOptions = response.data;
    });
    this.getDicts("DMC017").then(response => {
      this.frozenOptions = response.data;
    });

    const formData = new FormData();
    formData.append('code', 'DMC015');
    dmcTable(formData).then(response => {
        this.szEnableOptions = response.data;
    });
  },
  beforeUnmount() {
    // 在组件卸载之前清除定时器
    clearInterval(this.pollInterval);
  },
  computed: {
    disableParentSelect() {
      // 如果已选择用户有邀请人，则禁用邀请人选择框
      return this.form.user_id && this.getParentId(this.form.user_id) !== null && this.getParentId(this.form.user_id) !== '';
    }
  },
  methods: {
    columnStyle({ row, column, rowIndex, columnIndex }) {
          if (columnIndex ==9||columnIndex ==11||columnIndex ==14) {
        return 'background:rgba(242, 246, 252);'
        }
    },
    /** 查询数字直播列表 */
    getList() {
      this.loading = true;
      listLivestreaming(this.queryParams).then(response => {
        this.livestreamingList = response.rows;
        this.total = response.total;
        this.szWithdrawalBalanceSum=response.szWithdrawalBalanceSum;
        this.szWalletBalanceSum=response.szWalletBalanceSum;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.bugOpen = false;
      this.bugOpenDK = false;
      this.duichongDialogVisible = false;
      this.duichongDialogVisible2 = false;
      this.tixianDialogVisible = false;
      this.dashagnDialogVisible = false;
      this.reset();
      this.resetDuiChong();
      this.resetTixian();
      this.resetDashang();
    },
    // 购买产品 表单重置
    reset() {
      this.form = {
        user_id: null,
        parent_id: null,
        buy_type: null,
        energy: null,
        amount: null,
        deductionAmount: null
      };
      this.resetForm("form");
    },
    // 对冲产品 表单重置
    resetDuiChong(){
      this.duichongForm = {
        fromUser: "",
        toUser: "",
        buy_type: null,
        energy: null
      };
      this.resetForm("duichongForm");
    },
    // 对冲提现余额 表单重置
    resetDuiChong2(){
      this.duichongForm2 = {
        fromUser: "",
        toUser: "",
        money: null,
        paymentPassword: null
      };
      this.resetForm("duichongForm2");
    },
    // 提现 表单重置
    resetTixian(){
      this.tixianForm = {
        userId: "",
        amount: "",
        paymentPassword: "",
        remark: "",
        revenueRatio: null,
        extractRatio: null
      };
      this.resetForm("tixianForm");
    },
    // 打赏 表单重置
    resetDashang(){
      this.dashangForm = {
        userId: "",
        rewardedUser: "",
        giftId: "",
        price: "",
        count: ""
      },
      this.resetForm("dashangForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    // 用户选择框change事件处理
    handleUserChange(){
      const formData = new FormData();
      formData.append('userId', this.form.user_id);
      listSzUserSimple(formData).then(response => {
        this.parentOptions = response.data;
        const selectedUserId = this.form.user_id;
        const parentId = this.getParentId(selectedUserId);
        this.form.parent_id = Number(parentId);
        if(this.form.parent_id == 0){
          this.form.parent_id = null;
        }
      })
    },
    getParentId(userId) {
      // 根据用户ID获取对应的邀请人ID
      const selectedUser = this.userOptions.find(user => user.id === userId);
      return selectedUser ? selectedUser.parentId : null;
    },
    /** 购买按钮弹框 */
    handleAdd() {
      this.bugType = 1;
      getOtherRule().then(response => {
        this.form.buy_type = response.data.pricing;
        this.form.energy = response.data.energy;
      });

      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
      })

      const formData = new FormData();
      formData.append('userId', this.form.user_id);
      listSzUserSimple(formData).then(response => {
        this.parentOptions = response.data;
      })

      this.reset();
      this.submittingLoding = false;
      this.bugOpen = true;
      this.title = "购买数字人直播";
    },
    // 购买按钮弹框 免支付
    handleAddMM() {
      this.bugType = 2;
      getOtherRule().then(response => {
        this.form.buy_type = response.data.pricing;
        this.form.energy = response.data.energy;
      });

      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
      })

      const formData = new FormData();
      formData.append('userId', this.form.user_id);
      listSzUserSimple(formData).then(response => {
        this.parentOptions = response.data;
      })

      this.reset();
      this.submittingLoding = false;
      this.bugOpen = true;
      this.title = "购买数字人直播（免支付）";
    },
    // 购买按钮弹框 抵扣支付
    handleAddDK() {
      this.reset();

      getOtherRule().then(response => {
        this.form.buy_type = response.data.pricing;
        this.form.energy = response.data.energy;
      });

      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
      })

      const formData = new FormData();
      formData.append('userId', this.form.user_id);
      listSzUserSimple(formData).then(response => {
        this.parentOptions = response.data;
      })

      this.submittingLoding = false;
      this.bugOpenDK = true;
    },
    /** 对冲产品弹框 弹出 **/
    handleDuiChong(){
      getOtherRule().then(response => {
        this.duichongForm.buy_type = response.data.pricing;
        this.duichongForm.energy = response.data.energy;
      });

      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
        this.parentOptions = response.data;
      })

      this.resetDuiChong();
      this.submittingLoding = false;
      this.duichongDialogVisible = true;
    },
    /** 对冲提现余额弹框 弹出 **/
    handleDuiChong2(){
      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
        this.parentOptions = response.data;
      })

      this.resetDuiChong2();
      this.submittingLoding = false;
      this.duichongDialogVisible2 = true;
    },
    /** 提现弹框 弹出 **/
    handleTixian(){
      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
      })

      this.resetTixian();
      getOtherRule().then(response => {
        this.tixianForm.revenueRatio = response.data.revenue_ratio * 100 + '%';
        this.tixianForm.extractRatio = response.data.extract_ratio * 100 + '%';
      });
      this.submittingLoding = false;
      this.tixianDialogVisible = true;
    },
    /** 打赏弹框 弹出 **/
    handleDashang(){
      const formData1 = new FormData();
      formData1.append('userId', null);
      listSzUserSimple(formData1).then(response => {
        this.userOptions = response.data;
      })

      getSzGift().then(response => {
        this.giftList = response.data;
      })

      getSzanchor().then(response => {
        this.zbList = response.data;
      })

      this.resetDashang();
      this.submittingLoding = false;
      this.dashagnDialogVisible = true;
    },
    /** 查看邀请人 */
    handleShowInvite(row) {
      const id = row.id

      const formData2 = new FormData();
      formData2.append('userId', id);
      userInviteTree(formData2).then(response => {
        this.inviteUserList = response.data;
      })

      this.dialogVisibleInviteTitle = `用户${row.nickname}下级用户`
      this.dialogVisibleInvite = true;
    },
    // 查看购买记录
    handleShowPurchaseRecord(row){
      const id = row.id

      const formData = new FormData();
      formData.append('userId', id);
      purchaseRecordToAdmin(formData).then(response => {
        this.purchaseRecordList = response.data.list;
      })

      this.dialogVisiblePurchaseRecordTitle = `用户${row.nickname}的购买记录`
      this.dialogVisiblePurchaseRecord = true;
    },
    // 查看余额变动
    handleShowBalance(row){
      const id = row.id

      const formData = new FormData();
      formData.append('userId', id);
      balanceDetailAdmin(formData).then(response => {
        this.balanceDetailList = response.data.list;
        if(response.data.amount != null){
          this.income = response.data.amount.income;
          this.disburse = response.data.amount.disburse;
        }else{
          this.income = 0;
          this.disburse = 0;
        }
      })

      this.dialogVisibleBalanceDetailTitle = `用户${row.nickname}的余额变动记录`
      this.dialogVisiblBbalanceDetail = true;
    },
    // 查看提现余额变动
    handleShowWithdrawalBalance(row){
      const id = row.id

      const formData = new FormData();
      formData.append('userId', id);
      withdrawalBalance(formData).then(response => {
        this.withdrawalBalanceList = response.data.list;
        if(response.data.amount != null){
          this.income = response.data.amount.income;
          this.disburse = response.data.amount.disburse;
        }else{
          this.income = 0;
          this.disburse = 0;
        }
      })

      this.withdrawalBalanceTitle = `用户${row.nickname}的可提现余额变动记录`
      this.withdrawalBalanceDialogVisible = true;
    },
    /** 冻结、开启 按钮操作 */
    frozenOrEnable(row) {
      this.$confirm('确定要'+ (row.isFrozen==='0'?' 冻结 ':' 开启 ') + row.nickname +'的数字人直播产品吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const formData = new FormData();
          formData.append('id', row.id);
          formData.append('type', row.isFrozen === '0' ? '1' : '0');
          return frozenOrEnable(formData);
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        }).catch(() => {});
    },
    // 打开代理等级弹框
    vipUpgradeRecord(row){
      this.submittingLoding = false;
      const id = row.id

      const formData = new FormData();
      formData.append('userId', id);
      vipUpgradeRecord(formData).then(response => {
        this.vipRecordList = response.data;
      })

      listSzVipRule().then(response => {
        this.agencyOptions = response.data;
      });

      this.selectUser = id;
      this.selectVip = row.szAgency;
      this.dialogVisibleVIP = true;
    },
    // 打开抵扣还款弹框
    deductionRecord(row){
      this.submittingLoding = false;
      this.kyje = row.szWithdrawalBalance - row.frozenAccount;
      const id = row.id;

      if(row.szWithdrawalBalance <= row.deductionAmount){
        this.inputDeductionAmount = this.kyje;
      }else{
        this.inputDeductionAmount = row.deductionAmount;
      }

      // 查询抵扣金额记录
      const formData = new FormData();
      formData.append('userId', id);
      deductionAmountRecord(formData).then(response => {
        this.deductionList = response.data;
      })
      this.selectUser = id;
      this.dialogDeduction = true;
    },
    // 修改代理等级
    updateUserVip(){
      this.submittingLoding = true;
      const formData = new FormData();
      formData.append('userId', this.selectUser);
      formData.append('vipId', this.selectVip);
      updateUserVip(formData).then(response => {
          this.msgSuccess("操作成功");
          this.submittingLoding = false;
          this.dialogVisibleVIP = false;
          this.getList();
      });
    },
    // 抵扣还款
    updateDeduction(){
      this.submittingLoding = true;
      const formData = new FormData();
      formData.append('userId', this.selectUser);
      formData.append('amount', this.inputDeductionAmount);
      updateDeduction(formData).then(response => {
          this.msgSuccess("操作成功");
          this.submittingLoding = false;
          this.dialogDeduction = false;
          this.getList();
      });
    },
    /** 购买按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submittingLoding = true;

          if(this.bugType === 2 ){
            const formData = new FormData();
            formData.append('userId', this.form.user_id);
            formData.append('parentId', this.form.parent_id);
            buyLivestreaming(formData).then(response => {
                this.msgSuccess("购买成功");
                this.submittingLoding = false;
                this.bugOpen = false;
                this.getList();
            });
          }else{
            const formData = new FormData();
            formData.append('userId', this.form.user_id);
            formData.append('parentId', this.form.parent_id);
            createOrder(formData).then(response => {
              this.orderInfo.orderName = response.orderName;
              this.orderInfo.orderDescription = response.orderDescription;
              this.orderInfo.orderId = response.orderId;
              this.orderInfo.expirationTime = response.expirationTime;
              this.orderInfo.PaymentQRCode = 'data:image/png;base64,' + response.PaymentQRCode;
              this.dialogVisibleOrder = true;

              // 开始支付状态轮询
              this.startPolling(this.orderInfo.orderId);
            })
          }
        }
      })
    },
    /** 购买按钮 - 抵扣支付*/
    submitFormDK() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submittingLoding = true;

          const formData = new FormData();
          formData.append('userId', this.form.user_id);
          formData.append('parentId', this.form.parent_id);
          formData.append('amount', this.form.amount);
          formData.append('deductionAmount', this.form.deductionAmount);
          deductionBuyLivestreaming(formData).then(response => {
              this.msgSuccess("购买成功");
              this.submittingLoding = false;
              this.bugOpenDK = false;
              this.getList();
          });
        }
      })
    },
    // 轮询订单支付结果
    startPolling(orderId) {
      // 如果之前存在定时器，先清除
      if (this.pollInterval) {
        clearInterval(this.pollInterval);
      }

      // 开始支付状态轮询
      this.pollingCount = 0; // 重置轮询计数
      this.pollInterval = setInterval(() => {
        // 发送异步请求检查支付状态
        this.checkPaymentStatus(orderId)
          .then(status => {
            if (status === true) {
              // 支付成功时停止轮询
              clearInterval(this.pollInterval);
              // 设置支付状态为成功
              this.getList();
              this.msgSuccess("支付成功");
              this.dialogVisibleOrder = false;
              this.bugOpen = false;
            } else if (this.pollingCount >= this.maxPollingCount) {
              // 达到最大轮询次数时停止轮询
              clearInterval(this.pollInterval);
              // 设置支付状态为失败
            } else {
              // 继续轮询
              this.pollingCount++;
            }
          })
          .catch(error => {
            console.error('检查支付状态出错：', error);
            // 发生错误时停止轮询
            clearInterval(this.pollInterval);
            // 设置支付状态为失败
          });
      }, 1000); // 每秒进行一次轮询
    },
    checkPaymentStatus(orderId) {
      return new Promise((resolve, reject) => {
          // 发送异步请求检查支付状态
          const formData = new FormData();
          formData.append('orderId', orderId);
          orderPolling(formData).then(response => {
            const status = response.data;
            resolve(status);
          })
      });
    },
    /** 数字直播对冲产品确认按钮 **/
    submitFormDuiChong() {
      this.$refs["duichongForm"].validate(valid => {
        if (valid) {
          this.submittingLoding = true;

          const formData = new FormData();
          formData.append('fromUser', this.duichongForm.fromUser);
          formData.append('toUser', this.duichongForm.toUser);
          mutualRecharge(formData).then(response => {
              this.msgSuccess("购买成功");
              this.duichongDialogVisible = false;
              this.submittingLoding = false;
              this.getList();
            });
        }
      });
    },
    /** 数字直播对冲提现余额确认按钮 **/
    submitFormDuiChong2() {
      this.$refs["duichongForm2"].validate(valid => {
        if (valid) {
          this.submittingLoding = true;

          const formData = new FormData();
          formData.append('fromUser', this.duichongForm2.fromUser);
          formData.append('toUser', this.duichongForm2.toUser);
          formData.append('money', this.duichongForm2.money);
          formData.append('paymentPassword', this.duichongForm2.paymentPassword);
          mutualRechargeBalance(formData).then(response => {
              this.msgSuccess("操作成功");
              this.duichongDialogVisible2 = false;
              this.submittingLoding = false;
              this.getList();
            });
        }
      });
    },
    /** 提现按钮操作 */
    submitFormTixian() {
      this.submittingLoding = true;
      const formData = new FormData();
      formData.append('userId', this.tixianForm.userId);
      formData.append('amount', this.tixianForm.amount);
      formData.append('paymentPassword', this.tixianForm.paymentPassword);
      formData.append('remark', this.tixianForm.remark);
      balanceWithdrawal(formData).then(response => {
        this.msgSuccess("提现订单提交成功！");
        this.tixianDialogVisible = false;
        this.submittingLoding = false;
        this.getList();
      });
    },
    /** 打赏按钮操作 */
    submitFormDashang() {
      this.submittingLoding = true;
      const formData = new FormData();
      formData.append('userId', this.dashangForm.userId);
      formData.append('rewardedUser', this.dashangForm.rewardedUser);
      formData.append('giftId', this.dashangForm.giftId);
      formData.append('price', this.dashangForm.price);
      formData.append('count', this.dashangForm.count);
      rewardWithGifts(formData).then(response => {
        this.msgSuccess("打赏成功");
        this.dashagnDialogVisible = false;
        this.submittingLoding = false;
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有数字直播数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportLivestreaming(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    handleH5(){
      this.dialogVisibleH5 = true;

      const formData = new FormData();
          formData.append('userId', 1);
      createOrderH5().then(resp => {
        console.log(resp);
        this.test1 = resp.data.charset;
        this.test2 = resp.data.data;
        this.test3 = resp.data.signType;
        this.test4 = resp.data.sign;
      })
    },
    // 选择礼物
    changeGift(){
      const filteredGift = this.giftList.find(item => item.id === this.dashangForm.giftId);
      this.dashangForm.price = filteredGift.realPrice;
    },
    // 抵扣支付，更新抵扣金额
    changeAmount(){
      this.form.deductionAmount = this.form.buy_type - this.form.amount;
    }

  }
}
</script>
<style scoped>
.order-info {
  margin-bottom: 20px;
}

.payment-qrcode img {
  max-width: 100%;
  height: auto;
}

order-info-left {
  width: 100px;
}
.centered-text {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
